package com.shop.shopserver.websocket;

import com.shop.shopcommon.properties.WebSocketProperties;
import com.shop.shopcommon.utils.SpringContextUtil;
import com.shop.shoppojo.entity.HotSearch;
import com.shop.shopserver.handler.WebSocketSessionHandler;
import com.shop.shopserver.mapper.HotSearchMapper;
import com.shop.shopserver.service.HotSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
@ServerEndpoint("/hot-search-ws")
public class WebSocketServerSearch {
    @Autowired
    private HotSearchService hotSearchService;
    @Autowired
    private WebSocketProperties webSocketProperties;

    private static Set<Session> sessions = new HashSet<>();
    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
        log.info("/hot-search-ws WebSocket连接已建立 session: "+ session);
        // 手动获取service
        hotSearchService = SpringContextUtil.getBean(HotSearchService.class);
        webSocketProperties = SpringContextUtil.getBean(WebSocketProperties.class);
        sendHotSearches();
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        // 可添加处理客户端消息逻辑，此处暂不处理
    }

    @OnClose
    public void onClose(Session session) {
        // 连接关闭处理逻辑
    }

    @OnError
    public void onError(Session session, Throwable error) {
        // 错误处理逻辑
        error.printStackTrace();
    }

    private void sendHotSearches() {
        try {
            List<HotSearch> randomHotSearches = hotSearchService.getRandomHotSearches(webSocketProperties.getSearchIndexNumber()); // 获取5个随机热门搜索词
            String hotSearchList = randomHotSearches.stream()
                    .map(HotSearch::getText)
                    .collect(Collectors.joining("\n"));
            log.info("/hot-search-ws为搜索列表推送热搜推荐词条："+hotSearchList);
            for (Session s : sessions){
                if (s.isOpen()){
                    s.getBasicRemote().sendText(hotSearchList);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 定时任务，每*秒获取并发送随机热门搜索词
    @Scheduled(cron = "0 */5 * * * *")
    public void updateAndSendHotSearches() {
        sendHotSearches();
    }

}
